package com.base.myproject.client.HR.bcode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.Editdisable;
import com.base.myproject.client.busi.LasyObejct;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class Bcode_salary extends LayoutContainer implements LasyObejct{

	BaseStore<BusiObject> mainstore = null;
	BaseComboBoxForm<BaseModelData> C_num26 ;
	BaseComboBoxForm<BaseModelData> C_num27;
	BaseComboBoxX C_num30 ;//工资策略
	NumberField  C_num31;//工资
	BaseComboBoxForm<BaseModelData> C_dep ;//上级部门  
	TextField<String> C_num25;//识别码
	BaseComboBoxForm<BaseModelData> C_num32 ;//个税策略
	ArrayList<BaseStore<BusiObject>> refresh_list = new ArrayList<BaseStore<BusiObject>>() ;
	Button modify = new Button("修改薪金");
	BcodeMain main;

	String bcode_HR="";
	String w_date="";//入职日期
	
	public Bcode_salary(BcodeMain main) {
		this.main = main;
		this.mainstore = main.getStore();
		init();
	}

	void init() {
		initwidget();
		modify.addListener(Events.OnClick, getListener());
	}
	Widget initwidget() {
		FieldSet fs1 = new FieldSet();
		fs1.add(createForm());
		fs1.setHeading("薪金信息");
		FieldSet fs2 = new FieldSet();
		fs2.add(creatAllowanceeGrid());
		fs2.setHeading("薪金记录");
		
		VerticalPanel v = new VerticalPanel();
		v.setSpacing(2);
		v.add(fs1);
		v.add(fs2);
		this.add(v);
		return null;
	}
	/********/
	BaseFormPanel form;
	BaseFormPanel createForm() {
		form = new BaseFormPanel(mainstore);
		form.setBodyBorder(false);
		form.setPadding(6);
		form.setStyleName("form_css2");
		TableLayout tl = new TableLayout(6);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		
		
		form.add(new Label("薪金:"), td);
		C_num31 = new NumberField();
		C_num31.setFormat(NumberFormat.getFormat("0.00"));
		C_num31.setName("basesalary");
		C_num31.setAllowBlank(false);
		form.add(C_num31, td);
		form.add(modify, td);
		form.add(new Label("      "), td);
		form.add(new Label("      "), td);
		form.add(new Label("      "), td);
		
		form.add(new Label("银行:"), td);
		BaseComboBoxX C_num22 = new BaseComboBoxX("name","dictionary", "where type='hr_bank'");
		C_num22.setName("hr_bankno");
		form.add(C_num22, td);
		form.add(new Label("银行账户:"), td);
		TextField<String> C_num23 = new TextField<String>();
		C_num23.setWidth(150);
		C_num23.setName("hr_bankcard");
		form.add(C_num23, td);
		form.add(new Label("社保编号:"), td);
		TextField<String> C_num19 = new TextField<String>();
		C_num19.setName("hr_social_no");
		form.add(C_num19, td);
		
		form.setLayout(tl);
		form.setHeaderVisible(false);
		form.inited();
		return form;
	}
	/**********/
	BaseStore<BusiObject> Bcode_Employment_store = null;
	public BaseStore<BusiObject> getBcode_EmploymentStore() {
		if (Bcode_Employment_store == null) {
			createBcode_Employment_store();
		}
		return Bcode_Employment_store;
	}

	BaseStore<BusiObject> createBcode_Employment_store() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("paymethod");
		type.getField("paymethod").setType(String.class);
		type.addField("lastpaydate");
		type.getField("lastpaydate").setType(Date.class);
		type.addField("Insurancedate");
		type.getField("Insurancedate").setType(Date.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("bcode_job");
		info.setKeyname(new String[] { "icode" });
		info
				.setSql("select icode,bcode,lastpaydate,Insurancedate,paymethod" +
						" from bcode_job where bcode='{bcode}'");
		info.setParent(mainstore);// 关联主表
		info.setLinkparentcolumns(new String[] { "bcode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "bcode" });// 关联主表字段
		Bcode_Employment_store = new BaseStore<BusiObject>(type, info);
		return Bcode_Employment_store;
	}

	/**********************/
	BaseStore<BusiObject> bcode_Allowance_store = null;

	public BaseStore<BusiObject> get_bcode_Allowance_Store() {
		if (bcode_Allowance_store == null) {
			create_bcode_Allowance_Store();
		}
		return bcode_Allowance_store;
	}

	BaseStore<BusiObject> create_bcode_Allowance_Store() {
		
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("no_");
		type.getField("no_").setType(String.class);
		type.addField("desc_cn");
		type.getField("desc_cn").setType(String.class);
		type.addField("startdate");
		type.getField("startdate").setType(Date.class);
		type.addField("enddate");
		type.getField("enddate").setType(Date.class);
		type.addField("amount");
		type.getField("amount").setType(Double.class);
		type.addField("vprepare");
		type.getField("vprepare").setType(String.class);
		type.addField("modifydate");
		type.getField("modifydate").setType(String.class);
		type.addField("createdate");
		type.getField("createdate").setType(Date.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("bcode_Allowance");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from bcode_Allowance where bcode ='{bcode}' and status =0 and amount <> 0");
		info.setParent(mainstore);// 关联主表
		info.setLinkparentcolumns(new String[] { "bcode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "bcode" });// 关联主表字段
		bcode_Allowance_store = new BaseStore<BusiObject>(type, info);
		bcode_Allowance_store.addEditdisableItem(new Editdisable("no_", "A",
				BaseStore.EditDisableType.IN));
		return bcode_Allowance_store;
	}
	BaseGrid<BusiObject> bcode_Allowance_grid = null;
	NumberField amount ;
	public BaseGrid<BusiObject> creatAllowanceeGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C3 = new ColumnConfig("no_", "薪金编码", 80);
		BaseComboBoxForm<BaseModelData> bsb2 = new BaseComboBoxForm<BaseModelData>("code","desc_cn","hr_Salary_Item","",true);
		C3.setEditor(bsb2.getCelEditor());
		C3.setRenderer(bsb2);
		columns.add(C3);
		
		ColumnConfig C5 = new ColumnConfig("startdate", "生效开始日期", 100);
		DateField date1 = new DateField();
		date1.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		C5.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		C5.setEditor(new CellEditor(date1));
		columns.add(C5);
		
		ColumnConfig C6 = new ColumnConfig("enddate", "截止日期", 100);
		date1 = new DateField();
		date1.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		C6.setEditor(new CellEditor(date1));
		C6.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C6);
		
		ColumnConfig C7 = new ColumnConfig("amount", "金额", 80);
		C7.setNumberFormat(NumberFormat.getFormat("0.00"));
		NumberField nf = new NumberField();
		nf.setFormat(NumberFormat.getFormat("0.00"));
		C7.setEditor(new CellEditor(nf));
		columns.add(C7);
		
		ColumnModel cm = new ColumnModel(columns);
		bcode_Allowance_grid = new BaseGrid<BusiObject>(get_bcode_Allowance_Store(), cm,true,true);
		cbs.setSelectionMode(SelectionMode.SINGLE);
		bcode_Allowance_grid.setSelectionModel(cbs);
		bcode_Allowance_grid.setHeight(200);
		return bcode_Allowance_grid;
	}

	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.OnClick) {
							String bcode = mainstore.getValue("bcode").toString();
							String salary = C_num31.getRawValue();
							updateSalary(bcode, salary);
						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13){ // 回车
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}
	
	/**
	 * @param bcode 修改薪金的人员编码
	 * @param salary 修改后的薪金数值
	 * 这个方法用于在入职后发现工资输入错误，并且没发过工资或已经发了工资并且封存了的人员
	 * 进行薪金的修改，修改薪金的一系列操作（包括修改社保基数、工作经历等）
	 */
	private void updateSalary(final String bcode, final String salary) {
		 String hr_salary_ploy_m_sql = "select * from hr_salary where readOnly = '0' and bcode = '" + bcode + "'";
		   final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
		   greetingService2.getDataSet(hr_salary_ploy_m_sql, new AsyncCallback<DataSet>(){
			   @Override
			   public void onFailure(Throwable caught) {	
			   }
			   @Override
			   public void onSuccess(DataSet result) {	
				   if(result.getRowCount()>0){
					   MessageBox.alert("提示", "不能对已经发了工资且没有封存的员工进行薪金修改", null);
					   return;
				   }
				   
				   String updateBcode = "update bcode set basesalary = " + salary + " where bcode = '" + bcode + "'";
				   String updateEmployeeChange = "update hr_EmployeeChange set after = '" + salary + 
				   "' where bcode = '" + bcode + "' and remark = '入职' and ChangeType = '薪金'";  //只update入职时记录的薪金的工作记录
				   
				   String updateBaseSalary = "update hr_social_basedetail set socialbase = " + 
				   salary + " where bcode = '" + bcode + "'";  //因为之前也只进行有效的日期内的社保策略进行insert操作
				   												//，所以这次insert只需要根据BCODE去更新一条记录就行（因为只有唯一一条）
				   
				   //两条SQL都用之前的生效日期来判断用那个薪金策略来进行生成修改后的薪金
				   String updateSalary01 = "update bcode_Allowance set amount = (select case when baserate  >1 then baserate	 when baserate =-1 then  "+salary+"-isnull(positionrate, 0)-isnull(defined_salary3, 0)-isnull(defined_salary4,0) else "+salary+"*baserate end as amount from hr_salary_ploy where "+salary+">=salaryfrom and salaryto>"+salary+" and codename=(select top 1 codename from hr_salary_ploy_m where ploystartdate < startdate and (ployenddate > startdate or ployenddate is null ) order by ploystartdate)) where no_ = 'A01' and bcode = '" + bcode + "'";
				   String updateSalary05 = "update bcode_Allowance set amount = (select case when positionrate  >1 then positionrate 	 when positionrate =-1 then  "+salary+"-baserate-isnull(defined_salary3, 0)-isnull(defined_salary4,0) else "+salary+"*positionrate end as amount from hr_salary_ploy where "+salary+">=salaryfrom and salaryto>"+salary+" and codename=(select top 1 codename from hr_salary_ploy_m where ploystartdate < startdate and (ployenddate > startdate or ployenddate is null ) order by ploystartdate) and isnull(positionrate,0) != 0) where no_ = 'A05' and bcode = '" + bcode + "'";
				   
				   List<String> list = new ArrayList<String>();
				   list.add(updateBcode);
				   list.add(updateBaseSalary);
				   list.add(updateEmployeeChange);
				   list.add(updateSalary01);
				   list.add(updateSalary05);
				   
				   command(list);
			   }
		   });
	}
	
	private boolean command(List<String> lists) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		for (String sql : lists) {
			csql.getV().add(sql);
		}
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							if (result.isB()) {
								mainstore.reload();
								main.employ.getEmployeeChange(main
										.getTreeDepId(), main.getTreeDepName());
							} else {
								MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);

							}
						}
					});
		}
		return true;
	}
	
	@Override
	public boolean isopen() {
		return false;
	}

	@Override
	public boolean open() {
		return false;
	}
}
